package com.cxs.security;

import cn.hutool.json.JSONUtil;
import com.cxs.common.lang.Const;
import com.cxs.common.result.ResultVO;
import com.cxs.entity.User;
import com.cxs.service.IUserService;
import com.cxs.utils.JwtUtil;
import com.cxs.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    IUserService userService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if (authentication != null) {
            String username = (String) authentication.getPrincipal();
            User user = userService.getByUsername(username);
            redisUtil.hdel(Const.CACHE_KEY_AUTHORITY, user.getId().toString());
            redisUtil.hdel(Const.CACHE_KEY_MENU, user.getId().toString());

            // 手动退出
            new SecurityContextLogoutHandler().logout(request, response, authentication);
        }
        response.setContentType("application/json;charset=UTF-8");
        // 清除客户端的header中的jwt
        response.setHeader(jwtUtil.getHeader(), "");
        ServletOutputStream out = response.getOutputStream();

        ResultVO resultVO = new ResultVO<>("00000");
        out.write(JSONUtil.toJsonStr(resultVO).getBytes("UTF-8"));
        out.flush();
        out.close();
    }
}
